package com.atguigu.ssyx.activity.service.impl;

import com.atguigu.ssyx.activity.mapper.ActivityInfoMapper;
import com.atguigu.ssyx.activity.mapper.ActivityRuleMapper;
import com.atguigu.ssyx.activity.mapper.ActivitySkuMapper;
import com.atguigu.ssyx.activity.service.ActivityInfoService;
import com.atguigu.ssyx.client.product.ProductFeignClient;
import com.atguigu.ssyx.model.activity.ActivityInfo;
import com.atguigu.ssyx.model.activity.ActivityRule;
import com.atguigu.ssyx.model.activity.ActivitySku;
import com.atguigu.ssyx.model.product.SkuInfo;
import com.atguigu.ssyx.vo.activity.ActivityRuleVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-11-14
 */
@Service
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo> implements ActivityInfoService {

    @Resource
    private ActivityRuleMapper activityRuleMapper;

    @Resource
    private ActivitySkuMapper activitySkuMapper;

    @Resource
    private ProductFeignClient productFeignClient;

    /**
     * 获取活动列表
     * @param pageParam
     * @return
     */
    @Override
    public IPage<ActivityInfo> selectPage(Page<ActivityInfo> pageParam) {
        IPage<ActivityInfo> activityInfoPage = baseMapper.selectPage(pageParam, null);
        // 获取数据
        List<ActivityInfo> activityInfoList = activityInfoPage.getRecords();
        // 遍历,封装活动类型
        activityInfoList.forEach(item -> {
            item.setActivityTypeString(item.getActivityType().getComment());
        });
        return activityInfoPage;
    }

    /**
     * 根据活动id获取活动规则数据
     */
    @Override
    public Map<String, Object> findActivityRuleList(Long id) {
        Map<String, Object> result = new HashMap<>();
        // 根据活动id查询activity-rule表
        LambdaQueryWrapper<ActivityRule> ruleQueryWrapper = new LambdaQueryWrapper<>();
        ruleQueryWrapper.eq(ActivityRule::getActivityId, id);
        List<ActivityRule> activityRuleList = activityRuleMapper.selectList(ruleQueryWrapper);
        result.put("activityRuleList", activityRuleList);

        // 根据活动id查询规则商品skuId对应的列表activity-sku表
        LambdaQueryWrapper<ActivitySku> skuQueryWrapper = new LambdaQueryWrapper<>();
        skuQueryWrapper.eq(ActivitySku::getActivityId, id);
        List<ActivitySku> activitySkuList = activitySkuMapper.selectList(skuQueryWrapper);
        // 获取所有skuId
        List<Long> skuIdList = activitySkuList.stream().map(ActivitySku::getSkuId)
                .collect(Collectors.toList());
        // 远程调用service-product模块接口，根据skuId获取sku信息
        List<SkuInfo> skuInfoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(skuIdList)) {
            skuInfoList = productFeignClient.findSkuInfoList(skuIdList);
        }
        result.put("skuInfoList", skuInfoList);
        return result;
    }

    /**
     * 添加活动规则数据
     */
    @Override
    @Transactional
    public void saveActivityRule(ActivityRuleVo activityRuleVo) {
        Long activityId = activityRuleVo.getActivityId();
        // 删除旧的活动规则数据
        // 删除activity-rule表数据
        LambdaQueryWrapper<ActivityRule> ruleWrapper = new LambdaQueryWrapper<>();
        ruleWrapper.eq(ActivityRule::getActivityId, activityId);
        activityRuleMapper.delete(ruleWrapper);
        // 删除activity-sku表数据
        LambdaQueryWrapper<ActivitySku> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(ActivitySku::getActivityId, activityId);
        activitySkuMapper.delete(skuWrapper);

        // 获得新的规则数据
        List<ActivityRule> activityRuleList = activityRuleVo.getActivityRuleList();
        // 查询规则数据
        ActivityInfo activityInfo = baseMapper.selectById(activityId);
        //封装部分数据（活动id 和 活动类型）, 添加到activityRuleList
        activityRuleList.forEach(item -> {
            item.setActivityId(activityId);
            item.setActivityType(activityInfo.getActivityType());
            activityRuleMapper.insert(item);
        });

        // 获得规则范围列表
        List<ActivitySku> activitySkuList = activityRuleVo.getActivitySkuList();
        // 封装部分数据（活动id）,添加到activitySkuList
        activitySkuList.forEach(item -> {
            item.setActivityId(activityId);
            activitySkuMapper.insert(item);
        });
    }

    /**
     * 根据关键字查询匹配sku信息
     * @param keyword
     * @return
     */
    @Override
    @Transactional
    public List<SkuInfo> findSkuInfoByKeyword(String keyword) {
        // 根据输入的关键字查询sku匹配的信息
        /// service-product中创建远程调用接口：根据关键字查询匹配sku信息
        /// service-activity中远程调用service-product接口，获取匹配sku信息
        List<SkuInfo> skuInfoList = productFeignClient.findSkuInfoByKeyword(keyword);
        //判断：如果根据关键字查询不到匹配内容，直接返回空集合
        if (skuInfoList.isEmpty()) {
            return skuInfoList;
        }
        // 从skuInfoList集合中获取所有skuId
        List<Long> skuIdList = skuInfoList.stream().map(SkuInfo::getId).collect(Collectors.toList());

        // 判断商品是否参加过优惠活动，若已参与活动，则不能再次参与，排除商品
        /// 查询两张表数据：activity-sku表、activity-info表
        List<Long> skuIds = baseMapper.selectSkuIdList(skuIdList);
        /// 逻辑处理,排除已参加优惠活动商品
        List<SkuInfo> findSkuList = new ArrayList<>();
        // 遍历skuInfoList集合，根据skuId判断商品是否参加过优惠活动
        skuInfoList.forEach(item -> {
            if (!skuIds.contains(item.getId())) {
                findSkuList.add(item);
            }
        });
        return findSkuList;
    }
}
